<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleClick">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot:default="roleschild">
            <el-row
              :class="['ftagbd',i1===0?'ragbd':'', 'vcenter']"
              v-for="(item1,i1) in roleschild.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightsById(roleschild.row,item1.id)"
                >{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2===0 ? '' : 'ragbd', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightsById(roleschild.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightsById(roleschild.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="slotProps">
            <el-button
              icon="el-icon-edit"
              type="primary"
              size="mini"
              @click="editRoleClick(slotProps.row)"
            >编辑</el-button>
            <el-button
              icon="el-icon-delete"
              type="danger"
              size="mini"
              @click="delRoles(slotProps.row.id)"
            >删除</el-button>
            <el-button
              icon="el-icon-setting"
              type="warning"
              size="mini"
              @click="getRightsList(slotProps.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的对话框 -->
    <el-dialog title="提示" :visible.sync="showRightsDialog" width="50%">
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        ref="treeref"
        default-expand-all
        :default-checked-keys="defaultKeys"
        @close="removeDefKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRightsDialog = false">取 消</el-button>
        <el-button type="primary" @click="addCheckRights">确 定</el-button>
      </span>
    </el-dialog>
    <add-role :visible.sync="addRoleDialog" @addRuleSuccess="getRolesList()"></add-role>
    <edit-role
      :visible.sync="editRoleDialog"
      :userinfo="userInfo"
      @editRoleSuccess="getRolesList()"
    ></edit-role>
  </div>
</template>
<script>
import AddRole from '../../components/power/AddRole'
import EditRole from '../../components/power/EditRole'
export default {
  components: {
    AddRole,
    EditRole
  },
  data() {
    return {
      roleList: [],
      showRightsDialog: false,
      rightsList: [],
      // 树形结构数据
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点数据
      defaultKeys: [],
      roleId: '',
      addRoleDialog: false,
      editRoleDialog: false,
      userInfo: {}
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('角色列表数据获取失败')
      }
      this.roleList = res.data
    },
    async removeRightsById(role, rightid) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除的操作')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightid}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      role.children = res.data
    },
    // 弹出分配权限对话框并获取权限数据
    async getRightsList(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表数据失败')
      }
      this.rightsList = res.data
      this.getLeafKeys(role, this.defaultKeys)
      this.showRightsDialog = true
    },
    // 递归获取已有的权限列表
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 关闭对话框时候重置getLeafKeys数组
    removeDefKeys() {
      this.defaultKeys = []
    },
    // 提交权限分配的操作
    async addCheckRights() {
      const keys = [
        ...this.$refs.treeref.getCheckedKeys(),
        ...this.$refs.treeref.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('为角色分配权限失败')
      }
      this.$message.success('为角色分配权限成功')
      this.getRolesList()
      this.showRightsDialog = false
    },
    // 点击添加按钮
    addRoleClick() {
      this.addRoleDialog = true
    },
    // 删除角色
    async delRoles(id) {
      const delConfirm = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (delConfirm === 'cancel') {
        return this.$message.info('取消了删除的动作')
      }
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      this.$message.success('删除角色成功')
      this.getRolesList()
    },
    // 修改用户
    editRoleClick(userinfo) {
      this.userInfo = userinfo
      this.editRoleDialog = true
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.ragbd {
  border-top: 1px solid #eee;
}
.ftagbd {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
